package com.app.couponsharelife.ui.main.nativelife.activity

import android.content.Intent
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.manage.Contacts.USERID
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.LoadUtils
import com.tencent.mm.opensdk.modelbiz.AddCardToWXCardPackage
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_nativelife_details.*
import kotlinx.android.synthetic.main.base_title_white.*
import kotlinx.android.synthetic.main.lifereferrals_couponrvitm.view.*
import kotlinx.android.synthetic.main.nativelife_details_bannerrvitm.view.*
import kotlinx.android.synthetic.main.nativelife_details_hotrvitm.view.*
import java.text.DecimalFormat
import java.util.*

/**
 *Created by xct on 2019/1/10
 *Description:本地生活店铺详情页面
 */
class NativeLifeDetailsActivity:BaseActivity() {
    private var shopID=""
    private var imagList= arrayListOf<String>()
    private var couponList= arrayListOf<LifeDetailsRecord>()
    private var shopList= arrayListOf<LifeShopRecord>()
    private var myHotAdapter: MyHotAdapter?=null
    private var myCouponAdapter: MyCouponAdapter?=null
    private val decimalFormat= DecimalFormat("#.##")
    private var userID=""
    private var longitude=""
    private var latitude=""
    private var shopLatitude=""
    private var shopLongitude=""
    private var merchantID=""
    private var wxID=""
    private var isFirst=true
    override val viewLayoutId: Int
        get() = R.layout.activity_nativelife_details

    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        shopID=intent.getStringExtra("ShopID")
        userID=AppUtils.getString(USERID,"")
        longitude=AppUtils.getString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
        latitude=AppUtils.getString("Latitude",Contacts.HZ_CENTER_LATITUDE)
        lifereferrals_couponrv.layoutManager=LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
        myCouponAdapter=MyCouponAdapter()
        lifereferrals_couponrv.adapter=myCouponAdapter
        lifereferrals_couponrv.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                val layoutManager=recyclerView.layoutManager as LinearLayoutManager
                val firstPosition = layoutManager.findFirstCompletelyVisibleItemPosition()
                if(firstPosition==0) {
                    lifereferrals_couponrv.setType(false)
                }
                var lastPosition =layoutManager.findLastCompletelyVisibleItemPosition()
                if(lastPosition==layoutManager.itemCount -1) {
                    lifereferrals_couponrv.setType(false)
                }
            }
        })
        nativelife_details_hotrv.layoutManager=LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
        myHotAdapter=MyHotAdapter()
        nativelife_details_hotrv.adapter=myHotAdapter
        basetitle_llclose.setOnClickListener { finish() }
        getData()
        nativelife_details_name.setOnClickListener { startActivity(Intent(this,ShopGoodsDetailsActivity::class.java)) }
    }
    private fun setData(lifeShopRecord: LifeShopRecord){
        basetitle_title.text = lifeShopRecord.shopName
        nativelife_details_name.text=lifeShopRecord.shopName
        nativelife_details_address.text=lifeShopRecord.address
        shopLatitude=lifeShopRecord.latitude
        shopLongitude=lifeShopRecord.longitude
        var opentime=lifeShopRecord.openingTime
        if (opentime.isNotEmpty()&&opentime.length>16){
            opentime=opentime.substring(11,16)
        }else{
            opentime="00:00"
        }
        var closingtime=lifeShopRecord.closingTime
        if (closingtime.isNotEmpty()&&closingtime.length>16){
            closingtime=closingtime.substring(11,16)
        }else{
            closingtime="00:00"
        }
        nativelife_details_opentime.text="营业时间："+opentime+"-"+closingtime
        if (lifeShopRecord.activity!=null){
            nativelife_details_activitytext.text= Html.fromHtml("<font color=\"#9000FC\">#热门活动#</font>" + lifeShopRecord.activity!!.introduct)
            nativelife_details_activitytext1.text= Html.fromHtml("<font color=\"#9000FC\">#热门活动#</font>" + lifeShopRecord.activity!!.introduct)
        }
        if (lifeShopRecord.images.isNotEmpty()){
            imagList.addAll(lifeShopRecord.images.split(","))
            nativelife_details_bannerrv.layoutManager=LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
            nativelife_details_bannerrv.adapter=MyBannerAdapter()
        }
        nativelife_details_llphone.setOnClickListener {
            val phone=lifeShopRecord.phone
            if (phone.isNotEmpty()){
                AppUtils.callPhone(this,phone)
            }else{
                showToastMsg("该商家未提供联系方式！")
            }
        }
        getWxCardPage(lifeShopRecord.merchantId.toString(),lifeShopRecord.wxID)
        getShopList()
        getJL()
    }
    private fun getData(){
        showProgressDialog("请稍后...")
        val map= HashMap<String,String>()
        map["shopId"]=shopID
        RetrofitWorker.retrofitWorker.getShopInfo(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<LifeShopRecord>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<LifeShopRecord>) {
                        dismissProgressDialog()
                        if (it.code==200){
                            if (it.data!=null) {
                                setData(it.data!!)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)

                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    private fun getWxCardPage(merchantid:String,wxId:String){
        merchantID=merchantid
        wxID=wxId
        val map= HashMap<String,String>()
        map["pageNo"]="1"
        map["pageSize"]="10"
        map["sellerId"]=userID
        map["shopId"]=shopID
        map["merchantid"]=merchantid
        map["wxId"]=wxId
        RetrofitWorker.retrofitWorker.getWxCardPage(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<LifeDetailsCouponBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<LifeDetailsCouponBean>) {
                        if (it.code==200){
                            if (it.data!!.records!=null&&it.data!!.records!!.isNotEmpty()){
                                couponList.clear()
                                couponList.addAll(it.data!!.records!!)
                                myCouponAdapter!!.notifyDataSetChanged()
                            }else{
                                nativelife_details_clcoupon.visibility=View.GONE
                                nativelife_details_text.visibility=View.GONE
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        //Log.e("eeee","------>"+e.toString())
                        if (e is OtherException){
                            showToastMsg(e.msg)
                            nativelife_details_clcoupon.visibility=View.GONE
                            nativelife_details_text.visibility=View.GONE
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    private fun getShopList(){
        val map=HashMap<String,String>()
        map["pageNo"]="1"
        map["pageSize"]="10"
        map["Longitude"]=longitude
        map["Latitude"]=latitude
        map["status"]="7"
        map["distance"]="60"
        RetrofitWorker.retrofitWorker.lifeGetShopPage(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<LifeShopBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<LifeShopBean>) {
                        if (it.code==200){
                            if (it.data!=null&&it.data!!.records!=null&&it.data!!.records!!.isNotEmpty()){
                                shopList.clear()
                                shopList.addAll(it.data!!.records!!)
                                myHotAdapter!!.notifyDataSetChanged()
                            }else{
                                nativelife_details_hotrv.visibility=View.GONE
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (e is OtherException){
                            showToastMsg(e.msg)
                            nativelife_details_hotrv.visibility=View.GONE
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    private fun getWXExt(cardid: String,wxId:String){
        showProgressDialog("请稍后...")
        val map=HashMap<String,String>()
        map["wxid"]=wxId
        map["cardid"]=cardid
        map["userId"]=userID
        RetrofitWorker.retrofitWorker.getWxCardExt(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<WXExtBean>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: WXExtBean) {
                        dismissProgressDialog()
                        wxCard(it.cardid!!,it.cardext!!)
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private fun getJL(){
        val map= HashMap<String,String>()
        map["mode"]="driving"  //driving（驾车）、walking（步行）
        map["from"]= "$shopLatitude,$shopLongitude"   //from=39.071510,117.190091
        map["to"]="$latitude,$longitude"   //to=39.071510,117.190091;40.007632,117.190091
        map["key"]=Contacts.TXMAP_KEY    //开发密钥（Key）
        RetrofitWorker.retrofitWorker.getTXMapjl(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<TXResultBean<TXMapJLBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: TXResultBean<TXMapJLBean>) {
                        if (it.status==0&&it.result!=null&&it.result!!.elements!=null&&it.result!!.elements!!.isNotEmpty()){
                            val distance=it.result!!.elements!![0]!!.distance?:0.0
                            nativelife_details_tvjl.text=AppUtils.getKM(distance)
                        }
                    }

                    override fun onError(e: Throwable) {

                    }

                })
    }
    private fun wxCard(cardid:String,ext:String){
        val item= AddCardToWXCardPackage.WXCardItem()
        val cardItems= arrayListOf<AddCardToWXCardPackage.WXCardItem>()
        val req= AddCardToWXCardPackage.Req()
        val api= WXAPIFactory.createWXAPI(this, Contacts.WECHAT_APP_ID, false)
        item.cardId = cardid
        item.cardExtMsg = ext
        cardItems.add(item)
        req.cardArrary=cardItems
        api.sendReq(req)
    }

    override fun onResume() {
        super.onResume()
        if (!isFirst){
            if (merchantID.isNotEmpty()){
                getWxCardPage(merchantID,wxID)
            }
        }
        isFirst=false
    }

    /*override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val shopid=intent!!.getStringExtra("ShopID")?:""
        if (shopid.isNotEmpty()){
            shopID=shopid
            getData()
        }
    }*/
    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
    inner class MyBannerAdapter:RecyclerView.Adapter<MyBannerHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyBannerHolder {
            val view=LayoutInflater.from(parent.context).inflate(R.layout.nativelife_details_bannerrvitm,parent,false)
            return MyBannerHolder(view)
        }

        override fun getItemCount(): Int {
            return imagList.size
        }

        override fun onBindViewHolder(holder: MyBannerHolder, position: Int) {
            if (imagList.size>0){
                if (position==0){
                    holder.view.visibility=View.VISIBLE
                }else{
                    holder.view.visibility=View.GONE
                }
                LoadUtils().loadImag(this@NativeLifeDetailsActivity,holder.imag,imagList[position],R.drawable.ic_app_place_holder2)
            }
        }

    }
    inner class MyBannerHolder(itemView:View):RecyclerView.ViewHolder(itemView){
        val view= itemView.nativelife_details_bannerrvitm_zw!!
        val imag=itemView.nativelife_details_bannerrvitm_img
    }
    inner class MyCouponAdapter:RecyclerView.Adapter<MyCouponHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyCouponHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.lifereferrals_couponrvitm,parent,false)
            return MyCouponHolder(view)
        }

        override fun getItemCount(): Int {
            return couponList.size
        }

        override fun onBindViewHolder(holder: MyCouponHolder, position: Int) {
            if (couponList.isNotEmpty()){
                if (position==0){
                    holder.view!!.visibility=View.VISIBLE
                }else{
                    holder.view!!.visibility=View.GONE
                }
                var lifeWXCardBean=couponList[position]
                when(lifeWXCardBean.cardType){
                    "CASH"->{ // 代金券类型
                        holder.tvRMB!!.visibility=View.VISIBLE
                        holder.tvSm!!.text="满"+lifeWXCardBean.leastMoneyToUse+"可用"
                        holder.tvPrice!!.text=lifeWXCardBean.reduceMoney
                    }
                    "DISCOUNT"->{ //折扣券类型
                        holder.tvRMB!!.visibility=View.GONE
                        holder.tvSm!!.text="折扣券"
                        val zk=decimalFormat.format((lifeWXCardBean.discount/10))+"折"
                        holder.tvPrice!!.text=zk
                    }
                    "GIFT"->{ //兑换券类型
                        holder.tvRMB!!.visibility=View.GONE
                        holder.tvPrice!!.text="兑换券"
                        holder.tvSm!!.text="进店可兑换礼品"
                    }
                    else->{ //其他
                        holder.tvSm!!.text="满"+lifeWXCardBean.leastMoneyToUse+"可用"
                        holder.tvPrice!!.text=lifeWXCardBean.reduceMoney
                    }
                }
                if (lifeWXCardBean.wxUserCard!=null){
                    holder.imgYLQ!!.visibility=View.VISIBLE
                    holder.tvName!!.text="已领取"
                    holder.tvName!!.background=resources.getDrawable(R.drawable.shape_coupon_but_y)
                    holder.tvRMB!!.setTextColor(resources.getColor(R.color.golden_e3))
                    holder.tvPrice!!.setTextColor(resources.getColor(R.color.golden_e3))
                    holder.tvSm!!.setTextColor(resources.getColor(R.color.golden_e3))
                }else{
                    holder.imgYLQ!!.visibility=View.INVISIBLE
                    holder.tvName!!.text=lifeWXCardBean.shopName
                    holder.tvName!!.background=resources.getDrawable(R.drawable.shape_cc_e0_30)
                    holder.tvRMB!!.setTextColor(resources.getColor(R.color.golden_96))
                    holder.tvPrice!!.setTextColor(resources.getColor(R.color.golden_96))
                    holder.tvSm!!.setTextColor(resources.getColor(R.color.golden_96))
                }
                if (position == 0) {
                    holder.view!!.visibility = View.VISIBLE
                } else {
                    holder.view!!.visibility = View.GONE
                }
                holder.itemView.setOnClickListener {
                    if (lifeWXCardBean.wxUserCard==null){
                        getWXExt(lifeWXCardBean.cardId,lifeWXCardBean.wxid)
                    }
                }
            }
        }

    }
    inner class MyCouponHolder(itemView: View):RecyclerView.ViewHolder(itemView){
        var view:View?=null
        var tvPrice: TextView?=null
        var tvSm: TextView?=null
        var tvName: TextView?=null
        var imgYLQ: ImageView?=null
        var tvRMB: TextView?=null
        init {
            view=itemView.lifereferrals_couponitmzw
            tvPrice=itemView.lifereferrals_couponitm_price
            tvSm=itemView.lifereferrals_couponitm_gz
            tvName=itemView.lifereferrals_couponitm_name
            imgYLQ=itemView.lifereferrals_couponitm_ylq
            tvRMB=itemView.lifereferrals_couponitm_rmb
        }
    }
    inner class MyHotAdapter:RecyclerView.Adapter<MyHotHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHotHolder {
            val view=LayoutInflater.from(parent.context).inflate(R.layout.nativelife_details_hotrvitm,parent,false)
            return MyHotHolder(view)
        }

        override fun getItemCount(): Int {
            return shopList.size
        }

        override fun onBindViewHolder(holder: MyHotHolder, position: Int) {
            if (shopList.size>0){
                if (position==0){
                    holder.view.visibility=View.VISIBLE
                }else{
                    holder.view.visibility=View.GONE
                }
                val lifeShopRecord=shopList[position]
                val imagUrl = if (lifeShopRecord.images!=null&&lifeShopRecord.images.isNotEmpty()){
                    val imags=lifeShopRecord.images.split(",")
                    imags[0]
                }else{
                    lifeShopRecord.images?:""
                }
                LoadUtils().loadImag(this@NativeLifeDetailsActivity,holder.imageView,imagUrl,R.drawable.ic_app_place_holder2)
                holder.tvName.text=lifeShopRecord.shopName
                holder.tvAddress.text=lifeShopRecord.address
                holder.itemView.setOnClickListener {
                    val intent = Intent(this@NativeLifeDetailsActivity, NativeLifeDetailsActivity::class.java)
                    intent.putExtra("ShopID", lifeShopRecord.id)
                    startActivity(intent)
                    finish()
                }
            }
        }

    }
    inner class MyHotHolder(itemView: View):RecyclerView.ViewHolder(itemView){
        val view=itemView.nativelife_details_hotitmzw!!
        val imageView=itemView.nativelife_details_hotitmimg
        val tvName=itemView.nativelife_details_hotitmname
        val tvAddress=itemView.nativelife_details_hotitmaddress
    }
}